﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using OxyPlot.WindowsForms;
using OxyPlot.Legends;
using System.Timers;

namespace OPCService
{
    public partial class OxyPlotFrom : Form
    {
        private PlotModel plotModel;
        private LineSeries tempSeries;
        private LineSeries pressureSeries;
        private System.Timers.Timer dataTimer;
        private double timeCounter = 0;

        public OxyPlotFrom()
        {
            InitializeComponent();
            InitializePlot();
            InitializeTimer();
            this.Icon = new Icon("Resource/accs32.ico");
        }

        private void InitializePlot()
        {
            // 创建图表模型
            plotModel = new PlotModel
            {
                Title = "传感器数据可视化",
                //Subtitle = "温度与压力关系曲线",
                TitleFontSize = 16,
                SubtitleFontSize = 12,
                // 确保边距足够显示图例
                PlotMargins = new OxyThickness(60, 20, 20, 40),
                PlotAreaBorderThickness = new OxyThickness(1, 0, 0, 1) // 添加边框以便查看绘图区域
            };

            // 创建坐标轴
            var xAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                Title = "时间 (秒)",
                MajorGridlineStyle = LineStyle.Solid,
                MinorGridlineStyle = LineStyle.Dot
            };

            var yAxis1 = new LinearAxis
            {
                Position = AxisPosition.Left,
                Title = "温度 (°C)",
                Key = "Temperature",
                TitleColor = OxyColors.Red,
                TextColor = OxyColors.Red
            };

            var yAxis2 = new LinearAxis
            {
                Position = AxisPosition.Right,
                Title = "压力 (kPa)",
                Key = "Pressure",
                TitleColor = OxyColors.Blue,
                TextColor = OxyColors.Blue
            };

            plotModel.Axes.Add(xAxis);
            plotModel.Axes.Add(yAxis1);
            plotModel.Axes.Add(yAxis2);

            // 创建温度曲线系列
            tempSeries = new LineSeries
            {
                Title = "温度", // 必须设置Title才会显示在图例中
                StrokeThickness = 2,
                Color = OxyColors.Red,
                YAxisKey = "Temperature"
            };

            // 创建压力曲线系列
            pressureSeries = new LineSeries
            {
                Title = "压力", // 必须设置Title才会显示在图例中
                StrokeThickness = 2,
                Color = OxyColors.Blue,
                YAxisKey = "Pressure"
            };

            // 生成示例数据
            Random rand = new Random();
            for (double x = 0; x <= 20; x += 0.5)
            {
                tempSeries.Points.Add(new DataPoint(x, 25 + 10 * Math.Sin(x)));
                pressureSeries.Points.Add(new DataPoint(x, 100 + 30 * Math.Cos(x * 0.7) + (rand.NextDouble() - 0.5) * 5));
            }

            // 添加系列到模型
            plotModel.Series.Add(tempSeries);
            plotModel.Series.Add(pressureSeries);

            // 关键：正确添加图例 - 确保图例在可视区域内
            plotModel.Legends.Add(new Legend
            {
                LegendPosition = LegendPosition.RightTop,
                LegendPlacement = LegendPlacement.Outside, // 确保在绘图区域外
                LegendOrientation = LegendOrientation.Vertical,
                LegendBackground = OxyColor.FromArgb(220, 255, 255, 255), // 半透明背景
                LegendBorder = OxyColors.Gray,
                LegendBorderThickness = 1,

                // 确保图例不会太大而超出边界
                LegendMaxWidth = 100,
                LegendMaxHeight = 80
            });

            // 设置模型到PlotView
            plotView.Model = plotModel;
            timeCounter = 20;
        }

        private void InitializeTimer()
        {
            // 创建并配置定时器
            dataTimer = new System.Timers.Timer(500); // 500毫秒更新一次
            dataTimer.Elapsed += DataTimer_Elapsed;
            dataTimer.AutoReset = true;
            dataTimer.Start();
        }

        private void DataTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            // 在UI线程上更新数据
            this.Invoke(new Action(() =>
            {
                AddNewDataPoint();
            }));
        }

        private void AddNewDataPoint()
        {
            // 添加新数据点
            Random rand = new Random();
            tempSeries.Points.Add(new DataPoint(timeCounter, 25 + 10 * Math.Sin(timeCounter)));
            pressureSeries.Points.Add(new DataPoint(timeCounter, 100 + 30 * Math.Cos(timeCounter * 0.7) + (rand.NextDouble() - 0.5) * 5));

            // 增加时间计数器
            timeCounter++;

            // 限制数据点数量（可选）
            if (tempSeries.Points.Count > 50)
            {
                tempSeries.Points.RemoveAt(0);
            }
            if (pressureSeries.Points.Count > 50)
            {
                pressureSeries.Points.RemoveAt(0);
            }

            // 更新图表
            plotModel.InvalidatePlot(true);
        }

        // 窗体关闭时停止定时器
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            dataTimer?.Stop();
            dataTimer?.Dispose();
        }
    }
}
